package org.jeecg.modules.sistersophie.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.runtime.resource.loader.URLResourceLoader;

import java.io.StringWriter;
import java.util.Map;

/**
 * velocity引擎工具类
 * Created by sitou on 2017/10/15.
 */
public class VelocityUtil {


    public String convertTemplet(String templetUrl,Map<String,Object> params) {
        if(StringUtils.isBlank(templetUrl)){
            return null;
        }
        //int pathLastIndex = templetUrl.lastIndexOf("/");
       // String rootPath = templetUrl.substring(0,pathLastIndex);
        //String fileName = templetUrl.substring(pathLastIndex);
        StringWriter writer = new StringWriter();
        VelocityEngine vEngine = new VelocityEngine();
        vEngine.setProperty(Velocity.INPUT_ENCODING,"UTF-8");
        vEngine.setProperty(Velocity.OUTPUT_ENCODING,"UTF-8");
        vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        vEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        // vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,  "url");
       // vEngine.setProperty("url.resource.loader.class", URLResourceLoader.class.getName());
       // vEngine.setProperty("url.resource.loader.root",rootPath);
        vEngine.init();
        Template template = vEngine.getTemplate(templetUrl);
        VelocityContext context = new VelocityContext();
        if(params != null){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                context.put(entry.getKey(),entry.getValue());
            }
        }
        template.merge(context, writer);
        return writer.toString();
    }
}
